package com.executor.gateway.controller;

import com.executor.gateway.service.MetricsService;
import com.executor.gateway.service.impl.MetricsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 指标服务测试控制器
 * 用于测试指标服务的功能
 * 
 * @author miaoguoxin
 * @date 2024/01/01
 */
@RestController
@RequestMapping("/test/metrics")
@Slf4j
public class MetricsTestController {

    @Autowired
    private MetricsService metricsService;

    /**
     * 获取指标服务状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getMetricsStatus() {
        Map<String, Object> status = new HashMap<>();
        
        if (metricsService instanceof MetricsServiceImpl) {
            MetricsServiceImpl impl = (MetricsServiceImpl) metricsService;
            status.put("enhancedMode", impl.isEnhancedMode());
            status.put("serviceClass", impl.getClass().getSimpleName());
        } else {
            status.put("enhancedMode", false);
            status.put("serviceClass", metricsService.getClass().getSimpleName());
        }
        
        status.put("timestamp", LocalDateTime.now().toString());
        return ResponseEntity.ok(status);
    }

    /**
     * 切换指标服务模式
     */
    @PostMapping("/toggle-mode")
    public ResponseEntity<Map<String, Object>> toggleMode(@RequestParam boolean enhanced) {
        Map<String, Object> result = new HashMap<>();
        
        if (metricsService instanceof MetricsServiceImpl) {
            MetricsServiceImpl impl = (MetricsServiceImpl) metricsService;
            impl.setEnhancedMode(enhanced);
            
            result.put("success", true);
            result.put("enhancedMode", impl.isEnhancedMode());
            result.put("message", enhanced ? "Switched to enhanced mode" : "Switched to legacy mode");
            
            log.info("Metrics service mode switched to: {}", enhanced ? "enhanced" : "legacy");
        } else {
            result.put("success", false);
            result.put("message", "Mode switching not supported for current implementation");
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 测试传统模式的指标记录
     */
    @PostMapping("/test-legacy")
    public ResponseEntity<Map<String, Object>> testLegacyMetrics(@RequestParam String uri, @RequestParam String param) {
        try {
            metricsService.incOneCount2MetricsMap(uri, param);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "Legacy metrics recorded successfully");
            result.put("uri", uri);
            result.put("param", param);
            result.put("timestamp", LocalDateTime.now().toString());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error testing legacy metrics", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "Error recording legacy metrics: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 测试增强模式的指标记录
     */
    @PostMapping("/test-enhanced")
    public ResponseEntity<Map<String, Object>> testEnhancedMetrics() {
        try {
            LocalDateTime now = LocalDateTime.now();
            
            // 测试请求记录
            metricsService.recordRequest("test-service", "GET", "/test/path", "127.0.0.1", "TestAgent", now);
            
            // 测试响应记录
            metricsService.recordResponse("test-service", 200, 100L, now);
            
            // 测试API计数器
            metricsService.incrementApiCounter("/test/api", "request");
            
            // 测试API响应时间记录
            metricsService.recordApiResponseTime("/test/api", 150L);
            
            // 测试服务状态更新
            metricsService.updateServiceStatus("test-service", now);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "Enhanced metrics recorded successfully");
            result.put("timestamp", now.toString());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error testing enhanced metrics", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "Error recording enhanced metrics: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取API统计信息
     */
    @GetMapping("/api-stats")
    public ResponseEntity<Object> getApiStats(@RequestParam String apiPath) {
        try {
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime startTime = endTime.minusDays(1);
            
            Object stats = metricsService.getApiStatistics(apiPath, startTime, endTime);
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("Error getting API statistics", e);
            Map<String, String> error = new HashMap<>();
            error.put("error", "Failed to get API statistics: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取服务统计信息
     */
    @GetMapping("/service-stats")
    public ResponseEntity<Object> getServiceStats(@RequestParam String serviceId) {
        try {
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime startTime = endTime.minusDays(1);
            
            Object stats = metricsService.getServiceStatistics(serviceId, startTime, endTime);
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("Error getting service statistics", e);
            Map<String, String> error = new HashMap<>();
            error.put("error", "Failed to get service statistics: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 手动触发持久化
     */
    @PostMapping("/persist")
    public ResponseEntity<Map<String, Object>> persistMetrics() {
        try {
            metricsService.save2Db();
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "Metrics persisted successfully");
            result.put("timestamp", LocalDateTime.now().toString());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error persisting metrics", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "Error persisting metrics: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}